package com.wdf.dota;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.WeiXinShareContent;
import com.wdf.bean.Account;
import com.wdf.bean.DisscussionReply;
import com.wdf.bean.Page;
import com.wdf.bean.PostingDiscussion;
import com.wdf.helper.TimeUtils;
import com.wdf.rest.service.DotaDiscussionRestClient;

public class ForumViewActivity extends Activity {

	ListView listView;
	Button prevPageBtn;
	Button nextPageBtn;

	TextView forumPostingTitleView;
	TextView forumPostingContentView;
	TextView forumPostingAuthorView;

	TextView historyPageTv;

	List<PostingDiscussion> postingDiscussionsList;
	Page<PostingDiscussion> page;
	String loginName;
	String contactName;
	PostingDiscussionRestService postingDiscussionService;

	private BaseAdapter adapter;
	private static final int STATUS_CHANGE = 0;

	public Handler mHandler;

	String topic;
	String postingId;

	String title;
	String author;
	String content;

	Button submitDiscussionBtn;


	Button returnDiscussionBtn;

	LinearLayout pagnitationLinearLayout;
	
	TextView titleView;
	
	final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share",
            RequestType.SOCIAL);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		setContentView(R.layout.posting_discussion_list);
		listView = (ListView) findViewById(android.R.id.list);


		returnDiscussionBtn = (Button) findViewById(R.id.return_discussion);
		returnDiscussionBtn.setOnClickListener(returnDiscussionButtonListener);

		titleView = (TextView) findViewById(R.id.tv_wb);

		Bundle bundle = this.getIntent().getExtras();
		topic = bundle.getString("topic");
		postingId = bundle.getString("postingId");
		title = bundle.getString("title");
		content = bundle.getString("content");
		author= bundle.getString("author");
		
		handlerListHeaderView();

		if(topic!=null){
			titleView.setText(topic+"贴");
		}

		postingDiscussionService = new PostingDiscussionRestService(postingId);
		page = new Page<PostingDiscussion>();

		postingDiscussionsList = page.getResult();
		updateTextView();
		prevPageBtn.setOnClickListener(prevPageButtonListener);
		nextPageBtn.setOnClickListener(nextPageButtonListener);

		adapter = new DiscussionListAdapter(ForumViewActivity.this);
		listView.setAdapter(adapter);

		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case STATUS_CHANGE:
					// 处理UI更新等操作
					updateUI();
				}
			};
		};
		
		

		postingDiscussionService.getPostingDiscussions();
		

	//	mController.

	}
	
	public void handlerListHeaderView(){
		
		View header = LayoutInflater.from(this).inflate(R.layout.posting_discussion_list_header, null); 
		forumPostingTitleView = (TextView) header.findViewById(R.id.forumposting_title);
		forumPostingContentView = (TextView) header.findViewById(R.id.forumposting_content);
		forumPostingAuthorView = (TextView)header.findViewById(R.id.forumposting_author);
		
		forumPostingTitleView.setText(title);
		forumPostingContentView.setText("" + content);
		forumPostingAuthorView.setText("by  "+author+" ");
		listView.addHeaderView(header);
		
		View footer = LayoutInflater.from(this).inflate(R.layout.posting_discussion_list_footer, null); 
		pagnitationLinearLayout = (LinearLayout) footer.findViewById(R.id.pagnitation_linearLayout);
		historyPageTv = (TextView)footer. findViewById(R.id.history_page);
		prevPageBtn = (Button) footer.findViewById(R.id.chat_prev_page);
		nextPageBtn = (Button)footer.findViewById(R.id.chat_next_page);
		listView.addFooterView(footer);
	}


	OnClickListener prosterButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			SharedPreferences sharedPreferences = getSharedPreferences(
					"wonderful", Context.MODE_PRIVATE);
			String key = topic + "-" + postingId;
			int times = sharedPreferences.getInt(key, 0);
			if (times == 0) {
				postingDiscussionService.prosterPosting(postingId);

			} else {
				Toast.makeText(ForumViewActivity.this, "请勿重复评论!", 2).show();
			}

		}
	};

	OnClickListener supportButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			SharedPreferences sharedPreferences = getSharedPreferences(
					"wonderful", Context.MODE_PRIVATE);
			String key = topic + "-" + postingId;
			int times = sharedPreferences.getInt(key, 0);
			if (times == 0) {
				postingDiscussionService.supportPosting(postingId);

			} else {
				Toast.makeText(ForumViewActivity.this, "请勿重复评论!", 2).show();
			}

		}
	};



	private boolean validateComment(String id) {
		SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
				Context.MODE_PRIVATE);
		String key = "postingDiscussion" + "-" + id;
		int times = sharedPreferences.getInt(key, 0);
		if (times == 0) {
			return true;
		}
		Toast.makeText(this, "请勿重复评论!", 2).show();
		return false;
	}

	private void updateUI() {
		if (page.getResult().size() <= page.getPageSize()) {
			pagnitationLinearLayout.setVisibility(View.GONE);
		} else {
			pagnitationLinearLayout.setVisibility(View.VISIBLE);
		}
		// 详细的更新
		adapter.notifyDataSetChanged();// 更新ListView
		if (listView.getChildCount() > 0) {
			listView.setSelection(0);
		}
	//	setListViewHeight(listView);

		updateTextView();
	}

	/**
	 * 更新页码
	 */
	private void updateTextView() {
		if (postingDiscussionsList.size() == 0) {
			historyPageTv.setText(0 + "/" + 0);
		} else {
			historyPageTv.setText(page.getPageNo() + 1 + "/"
					+ page.getTotalPages());
		}

	}

	public class DiscussionListAdapter extends BaseAdapter {

		private class RecentViewHolder {
			TextView postingDiscussionIdView;
			TextView usernameView;
			TextView sender_context;
			TextView replyView;
			TextView rTime;
			Button supporter;
			Button protester;
			LinearLayout reply;
		}

		Context context;
		LayoutInflater mInflater;

		public DiscussionListAdapter(Context context) {
			this.context = context;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {

			return page.getDisplayCount();
		}

		@Override
		public Object getItem(int position) {
			return page.getItem(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			RecentViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.posting_discussion_item, null);
				holder = new RecentViewHolder();
				holder.postingDiscussionIdView = (TextView) convertView
						.findViewById(R.id.comment_id);
				holder.usernameView = (TextView) convertView
						.findViewById(R.id.username);
				holder.supporter = (Button) convertView
						.findViewById(R.id.supporter);
				holder.protester = (Button) convertView
						.findViewById(R.id.protester);
				holder.reply = (LinearLayout) convertView
						.findViewById(R.id.discussion_reply);
				holder.sender_context = (TextView) convertView
						.findViewById(R.id.message_view_sender_content);
				holder.rTime = (TextView) convertView
						.findViewById(R.id.message_view_timestamp);
				holder.replyView = (TextView) convertView
						.findViewById(R.id.message_view_sender_reply);
				convertView.setTag(holder);
			} else {
				holder = (RecentViewHolder) convertView.getTag();
			}
			PostingDiscussion postingDiscussion = (PostingDiscussion) getItem(position);
			final String postingDiscussionId = "" + postingDiscussion.getId();
			if (postingDiscussion != null) {
				holder.postingDiscussionIdView.setText(""
						+ postingDiscussion.getId());
				holder.sender_context.setText(""
						+ postingDiscussion.getContent());
				holder.rTime.setText(TimeUtils.timePast(postingDiscussion
						.getCreatetime()));
				holder.usernameView.setText(postingDiscussion.getAccount()
						.getUsername());
				holder.supporter.setText("赞("
						+ postingDiscussion.getSupporter() + ")");
				holder.protester.setText("踩("
						+ postingDiscussion.getProtester() + ")");
				StringBuffer sb = new StringBuffer();
				for (DisscussionReply reply : postingDiscussion
						.getDisscussionReply()) {
					sb.append( "<font size=3 color=#000000 >"+reply.getAccount().getUsername() + "</font> <font size=1 color=#484848 >回复:</font>  "
							+ "<font size=3 color=#000000 >"+reply.getContent() + "</font><br>");
				}
				holder.replyView.setText(Html.fromHtml(sb.toString()));
				holder.supporter.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (validateComment(postingDiscussionId)) {
							postingDiscussionService
									.supportDiscussion(postingDiscussionId);
						}
					}
				});
				holder.protester.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (validateComment(postingDiscussionId)) {
							postingDiscussionService
									.protestDiscussion(postingDiscussionId);
						}
					}
				});
				holder.reply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						SharedPreferences sharedPreferences = getSharedPreferences(
								"wonderful", Context.MODE_PRIVATE);
						String accountid = sharedPreferences.getString(
								"accountid", "0");
						String username = sharedPreferences.getString(
								"username", "");
						if ("0".equals(accountid) || username == null
								|| username.length() <= 0) {
							Intent intent = new Intent(ForumViewActivity.this,
									LoginActivity.class);
							startActivityForResult(intent, 4);
						} else {
							Intent intent = new Intent(ForumViewActivity.this,
									DiscussionReplyActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString("discussionId",
									postingDiscussionId);
							intent.putExtras(bundle);
							startActivityForResult(intent, 4);
						}

					}
				});
			}
			return convertView;
		}
	}

	public void setListViewHeight(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight =totalHeight + listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1))+100;
		listView.setLayoutParams(params);

	}

	/**
	 * 上一页按钮的监听事件
	 */
	OnClickListener prevPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (page.isHasPre()) {
				page.setPageNo(page.getPageNo() - 1);
				updateUI();
			}

		}
	};

	/**
	 * 下一页按钮的监听事件
	 */
	OnClickListener nextPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (page.isHasNext()) {
				page.setPageNo(page.getPageNo() + 1);
				updateUI();
			}

		}
	};

	OnClickListener returnDiscussionButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			ForumViewActivity.this.finish();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		postingDiscussionService.getPostingDiscussions();
	}

	class PostingDiscussionRestService {
		private String postingId;

		public PostingDiscussionRestService(String postingId) {
			this.postingId = postingId;
		}

		public void getPostingDiscussions() {
			final RequestParams params = new RequestParams();
			params.put("postingId", postingId);
			DotaDiscussionRestClient.get("/dota/postingdiscussions.json",
					params, new JsonHttpResponseHandler() {

						@Override
						public void onSuccess(JSONArray elements) {
							try {
								if (elements != null) {
									List<PostingDiscussion> postingDiscussions = new ArrayList<PostingDiscussion>();
									for (int i = 0; i < elements.length(); i++) {
										JSONObject object = elements
												.getJSONObject(i);
										JSONArray replys = object
												.getJSONArray("disscussionReply");

										PostingDiscussion postingDiscussion = new PostingDiscussion();
										for (int j = 0; j < replys.length(); j++) {
											JSONObject reply = replys
													.getJSONObject(j);
											String desc = reply
													.getString("content");
											JSONObject user = reply
													.getJSONObject("account");
											Account account = new Account();
											String username = user
													.getString("username");
											account.setUsername(username);
											DisscussionReply disscussionReply = new DisscussionReply();
											disscussionReply.setContent(desc);
											disscussionReply
													.setAccount(account);
											postingDiscussion
													.getDisscussionReply().add(
															disscussionReply);
										}

										postingDiscussion.setContent(object
												.getString("content"));
										postingDiscussion.setCreatetime(object
												.getString("createtime"));
										postingDiscussion.setId(object
												.getInt("id"));
										JSONObject user = object
												.getJSONObject("account");
										Account account = new Account();
										Integer userid = user.getInt("id");
										String username = user
												.getString("username");
										account.setId(userid);
										account.setUsername(username);
										postingDiscussion.setAccount(account);
										postingDiscussion.setProtester(object
												.getInt("protester"));
										postingDiscussion.setSupporter(object
												.getInt("supporter"));

										postingDiscussions
												.add(postingDiscussion);
									}
									postingDiscussionsList = postingDiscussions;
									page.setResult(postingDiscussions);
									page.setTotalCount(postingDiscussions
											.size());

									updateUI();
								}

							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					});

		}

		public void supportDiscussion(final String id) {
			final RequestParams params = new RequestParams();
			// params.put("commentId", id);
			DotaDiscussionRestClient.put(
					"/dota/postingdiscussions/support.json?discussionId=" + id,
					params, new JsonHttpResponseHandler() {

						@Override
						public void onSuccess(JSONObject object) {
							SharedPreferences sharedPreferences = getSharedPreferences(
									"wonderful", Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							String key = "postingDiscussion" + "-" + id;
							editor.putInt(key, 1);
							editor.commit();
							postingDiscussionService.getPostingDiscussions();

						}
					});

		}

		public void protestDiscussion(final String id) {
			final RequestParams params = new RequestParams();
			// params.put("commentId", id);
			DotaDiscussionRestClient.put(
					"/dota/postingdiscussions/protest.json?discussionId=" + id,
					params, new JsonHttpResponseHandler() {
						@Override
						public void onSuccess(JSONObject object) {
							SharedPreferences sharedPreferences = getSharedPreferences(
									"wonderful", Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							String key = "postingDiscussion" + "-" + id;
							editor.putInt(key, 1);
							editor.commit();
							postingDiscussionService.getPostingDiscussions();
						}
					});

		}

		public void supportPosting(final String id) {
			final RequestParams params = new RequestParams();
			// params.put("commentId", id);
			DotaDiscussionRestClient.put(
					"/dota/forumpostings/support.json?postingId=" + id, params,
					new JsonHttpResponseHandler() {

						@Override
						public void onSuccess(JSONObject object) {
							SharedPreferences sharedPreferences = getSharedPreferences(
									"wonderful", Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							String key = topic + "-" + id;
							editor.putInt(key, 1);
							editor.commit();
							Toast.makeText(ForumViewActivity.this, "点赞成功!", 2)
									.show();
						}
					});

		}

		public void prosterPosting(final String id) {
			final RequestParams params = new RequestParams();
			// params.put("commentId", id);
			DotaDiscussionRestClient.put(
					"/dota/forumpostings/protest.json?postingId=" + id, params,
					new JsonHttpResponseHandler() {

						@Override
						public void onSuccess(JSONObject object) {
							SharedPreferences sharedPreferences = getSharedPreferences(
									"wonderful", Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							String key = topic + "-" + id;
							editor.putInt(key, 1);
							editor.commit();
							Toast.makeText(ForumViewActivity.this, "反对成功!", 2)
									.show();
						}
					});

		}
	}
	
	public void myHandler(View v){
		switch(v.getId()){
		case R.id.socialShareLinearLayout:
		case R.id.socialShare:
			mController.setShareContent(title +"\n                     作者:"+author+"\n   "+content );
			mController.openShare(this, false);
			break;
		case R.id.submit_discussion:
		case R.id.submit_discussionLinearLayout:
			SharedPreferences sharedPreferences = getSharedPreferences(
					"wonderful", Context.MODE_PRIVATE);
			String accountid = sharedPreferences.getString("accountid", "0");
			String username = sharedPreferences.getString("username", "");

			if ("0".equals(accountid) || username == null
					|| username.length() <= 0) {
				Intent intent = new Intent(ForumViewActivity.this,
						LoginActivity.class);
				startActivityForResult(intent, 4);
			} else {
				Intent intent = new Intent(ForumViewActivity.this,
						SubmitPostingDiscussionActivity.class);
				Bundle bundle = ForumViewActivity.this.getIntent().getExtras();
				bundle.putString("postingId", postingId);
				bundle.putString("topic", topic);
				intent.putExtras(bundle);
				startActivityForResult(intent, 4);
			}
			break;
			
			
		
		}
		
	}

}